package interview.doublylinkedlist;

public class DoublyLinkedList {
	public Node root;

	public void add(Node toAdd) {
		if (toAdd == null) {
			return;
		}

		if (root == null) {
			root = toAdd;
			root.next = root;
			root.previous = root;
			return;
		}

		toAdd.next = root.next;
		toAdd.previous = root;
		root.next.previous = toAdd;
		root.next = toAdd;
	}

	public boolean remove(Node toRemove) {
		if (toRemove == null)
			return false;

		Node current = root;
		do {
			if (current == toRemove) {
				if (current == root && root.next == root && root.previous == root) {
					root = null;
					return true;
				}
				current.previous.next = current.next;
				current.next.previous = current.previous;
				if (current == root) {
					root = current.next;
				}
				return true;
			}
			current = current.next;
		} while (current != root);

		return false;
	}

	public int length() {
		if (root == null)
			return 0;

		Node current = root;
		int length = 1;
		while (current.next != root) {
			current = current.next;
			length++;
		}
		return length;
	}
}
